package edu.mama.college.service;

import edu.mama.college.mapper.CarouselMapper;
import edu.mama.college.model.Carousel;
import edu.mama.college.model.Course;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CarouselService {

    @Autowired
    private CarouselMapper carouselMapper;

    /**
     * 获取轮播图列表
     * @return
     */
    @Cacheable(value="Resource",key="'carousel'")
    public List<Carousel> getCarousels(){
        return carouselMapper.getCarousels();
    }

    /**
     * 调整轮播图
     */
    @Transactional
    @CachePut(value="Resource",key="'carousel'")
    public List<Carousel> updateCarousels(List<Map<String,String>> dataList) throws Exception {
        try{
            List<Carousel> carousels = dataList.stream().map(data->{
                return new Carousel(
                        Integer.parseInt(data.get("id")),
                        Integer.parseInt(data.get("sort")),
                        data.get("image"),
                        data.get("bgColor"),
                        data.get("link")
                );
            }).collect(Collectors.toList());
            carouselMapper.delete();
            carouselMapper.createCarousels(carousels);
            return carousels;
        }catch(Exception e){
            log.error("调整轮播图：",e);
            throw new Exception("调整轮播图失败");
        }
    }



}
